﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketHttpLib
{
    internal class StreamReadUtil
    {
        public static void StreamRead(Stream stream, MemoryStream ms, int offset, int size)
        {
            var bytesRead = 0;
            var totalBytesRead = 0;
            var buffer = new byte[size];
            while (totalBytesRead < size)
            {
                bytesRead = stream.Read(buffer, bytesRead, size - bytesRead);
                totalBytesRead += bytesRead;
                ms.Write(buffer, 0, bytesRead);
            }
        }

        public static MemoryStream ReadChunkedStream(HttpHelper helper, Stream input)
        {
            var ms = new MemoryStream();
            int chunkNum = 0;
            while (true)
            {
                var line = helper.ReadLine(input);
                var chunkHead = Encoding.ASCII.GetBytes(line + "\r\n");
                if (line.Length > 0)
                {
                    //ms.Write(chunkHead, 0, chunkHead.Length);
                    var chunckSize = Convert.ToInt32(line, 16);//4090,2874
                    if (chunckSize > 0)
                    {
                        var buffer = new byte[chunckSize];
                        using (var msChunck = new MemoryStream())
                        {
                            helper.StreamRead(input, msChunck, 0, chunckSize);
                            msChunck.CopyTo(ms);
                        }
                        line = helper.ReadLine(input);
                        chunkNum++;
                    }
                    else
                        break;
                }
                else
                    break;
            }
            ms.Position = 0;
            return ms;
        }
    }
}
